import React from 'react';
// import { Link } from 'react-router-dom';
import { Select, DatePicker } from 'antd';
import axios from 'axios';
import moment from 'moment';
import { apiPrefix } from 'shared/api';
import AlertModule from 'shared/AlertModule';

import './index.less';

const { Option } = Select;
const dateFormat = 'YYYY-MM-DD';

export default class Home extends React.PureComponent {
  constructor() {
    super();
    this.state = {
      visible: false,
      change: false,
      warn1: true,
      warn2: true,
      warn3: true,
      warn4: true,
      newContractManage: {
        number: '',
        descr: '',
      },
      people: [],
      categories: [],
      periods: [],
    };
  }
  componentDidMount() {
    const api = `${apiPrefix}api/v1/unirole/users`;
    const api2 = `${apiPrefix}api/v1/contract/categories`;
    const api3 = `${apiPrefix}api/v1/contract/periods`;
    axios.get(api)
      .then((response) => {
        this.setState({ people: response.data.data });
      });
    axios.get(api2)
      .then((response) => {
        this.setState({ categories: response.data.data });
      });
    axios.get(api3)
      .then((response) => {
        this.setState({ periods: response.data.data });
      });
    if (this.props.match.params.id !== undefined) {
      const api4 = `${apiPrefix}api/v1/contract/contract?id=${this.props.match.params.id}`;
      axios.get(api4)
        .then((response) => {
          this.setState({ newContractManage: response.data.data });
          console.log(response.data.data);
        });
    }
  }
  redirectToContractListPage() {
    this.props.history.push('/Contract/ContractListManage');
  }
  redirectTocontractManagePage() {
    this.props.history.push('/Contract/ContractListManage');
  }
  handlOnChange=(value, key) => {
    const { newContractManage } = this.state;
    newContractManage[key] = value;
    this.setState({ newContractManage: { ...this.state.newContractManage }, change: true });
  }
  showAlertModule=() => {
    if (this.state.change === true) {
      this.setState({ visible: true });
    } else {
      console.log(222);
      this.redirectToContractListPage();
    }
  }
  closeAlertModule=() => {
    this.setState({ visible: false });
  }
  historyPush=() => {
    this.redirectToContractListPage();
    this.setState({ visible: false });
  }
  sureAdd=() => {
    if (this.props.match.params.id === undefined) {
      const { newContractManage } = this.state;
      if (newContractManage.user_id === '' || newContractManage.user_id === undefined) {
        this.setState({ warn1: false });
      } else {
        this.setState({ warn1: true });
      }
      if (newContractManage.category_id === '' || newContractManage.category_id === undefined) {
        this.setState({ warn2: false });
      } else {
        this.setState({ warn2: true });
      }
      if (newContractManage.period_id === '' || newContractManage.period_id === undefined) {
        this.setState({ warn3: false });
      } else {
        this.setState({ warn3: true });
      }
      if (newContractManage.mfd_date === '' || newContractManage.mfd_date === undefined) {
        this.setState({ warn4: false });
      } else {
        this.setState({ warn4: true });
      }
      const api = `${apiPrefix}api/v1/contract/contract`;
      axios.post(api, {
        user_id: newContractManage.user_id,
        number: newContractManage.number,
        category_id: newContractManage.category_id,
        mfd_date: newContractManage.mfd_date,
        period_id: newContractManage.period_id,
        descr: newContractManage.descr,
      })
        .then((response) => {
          if (response.data.code === 200) {
            this.redirectTocontractManagePage();
          }
        });
    } else {
      const { newContractManage } = this.state;
      const api = `${apiPrefix}/api/v1/contract`;
      axios.put(api, {
        user_id: newContractManage.user_id,
        number: newContractManage.number,
        category_id: newContractManage.category_id,
        mfd_date: newContractManage.mfd_date,
        period_id: newContractManage.period_id,
        descr: newContractManage.descr,
      })
        .then(() => {
          this.redirectTocontractManagePage();
        });
    }
  }
  render() {
    const peopleList = this.state.people;
    const categoriesList = this.state.categories;
    const periodsList = this.state.periods;
    const id = this.props.match.params.id;
    const { newContractManage, visible } = this.state;
    console.log(newContractManage);
    return (
      <div className="addContractManage">
        <div className="contractManage">
          <div>
            <div>
              <h3>{id ? '编辑合同' : '添加新合同'}</h3>
            </div>
            <div className="manageContent" >
              <div>
                <span> 选择人员</span>
                <Select
                  showSearch
                  className={this.state.warn1 ? '' : 'borderRed'}
                  style={{ width: 200 }}
                  value={this.state.newContractManage.user_id}
                  placeholder="选择人员"
                  onChange={value => this.handlOnChange(value, 'user_id')}
                  optionFilterProp="children"
                  filterOption={(input, option) =>
                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                }
                >
                  {
                  peopleList.map((value, index) => (
                    <Option value={value.id} key={index}>{value.name}</Option>
                  ))
              }
                </Select>
                <span className="warnSpan">{this.state.warn1 ? '' : '*必须填'}</span>
              </div>
              <div>
                <span> 选择合同类型</span>
                <Select
                  showSearch
                  className={this.state.warn2 ? '' : 'borderRed'}
                  style={{ width: 200 }}
                  value={this.state.newContractManage.category_id}
                  placeholder="选择合同类型"
                  onChange={value => this.handlOnChange(value, 'category_id')}
                  optionFilterProp="children"
                  filterOption={(input, option) =>
                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                }
                >
                  {
                  categoriesList.map((value, index) => (
                    <Option value={value.id} key={index}>{value.name}</Option>
                  ))
              }
                </Select>
                <span className="warnSpan">{this.state.warn2 ? '' : '*必须填'}</span>
              </div>
              <div>
                <span> 选择合同期限</span>
                <Select
                  showSearch
                  className={this.state.warn3 ? '' : 'borderRed'}
                  style={{ width: 200 }}
                  value={this.state.newContractManage.period_id}
                  placeholder="选择合同期限"
                  onChange={value => this.handlOnChange(value, 'period_id')}
                  optionFilterProp="children"
                  filterOption={(input, option) =>
                option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                }
                >
                  {
                  periodsList.map((value, index) => (
                    <Option value={value.id} key={index}>{value.name}</Option>
                  ))
              }
                </Select>
                <span className="warnSpan">{this.state.warn3 ? '' : '*必须填'}</span>
              </div>
              <div>
                <span>合同编号</span>
                <input
                  type="text"
                  value={this.state.newContractManage.number}
                  onChange={e => this.handlOnChange(e.target.value, 'number')}
                  placeholder="请输入合同编号"
                />
                <span />
              </div>
              <div>
                <span>备注</span>
                <input
                  type="text"
                  value={this.state.newContractManage.descr || ''}
                  onChange={e => this.handlOnChange(e.target.value, 'descr')}
                  placeholder="请输入备注"
                />
                <span />
              </div>
              <div>
                <span>添加合同时间</span>
                <DatePicker
                  placeholder="添加合同时间"
                  style={{ margin: 0 }}
                  className={this.state.warn4 ? '' : 'borderRed'}
                  value={!this.state.newContractManage.mfd_date ? null : moment(this.state.newContractManage.mfd_date, dateFormat)}
                  format={dateFormat}
                  onChange={(date, dateString) => this.handlOnChange(dateString, 'mfd_date')}
                />
                <span className="warnSpan">{this.state.warn1 ? '' : '*必须填'}</span>
              </div>
            </div>
            <div className="sureButton">
              <button onClick={this.sureAdd} >保存</button>
              <a className="cancelM" onClick={this.showAlertModule}>取消</a>
              <AlertModule visible={visible} onCancel={this.closeAlertModule} onOk={this.historyPush} />
            </div>
          </div>
        </div>
      </div>
    );
  }
}
